package com.whfc.common.util;

import org.apache.commons.lang3.StringUtils;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/8/23 15:44
 */
public class VersionUtil {

    /**
     * 获取版本号
     *
     * @param verArr
     * @return
     */
    public static String getHardwareVersion(int[] verArr) {
        StringBuffer ver = new StringBuffer();
        if (verArr != null && verArr.length > 0) {
            for (int i = 0; i < verArr.length; i++) {
                if (i > 0) {
                    ver.append(".");
                }
                ver.append(verArr[i]);
            }
        }
        return ver.toString();
    }

    /**
     * @param ver
     * @return
     */
    public static int[] parseHardvareVersion(String ver) {
        if (!StringUtils.isEmpty(ver)) {
            String[] arr = ver.split("\\.");
            if (arr != null && arr.length > 0) {
                int[] verArr = new int[arr.length];
                for (int i = 0; i < verArr.length; i++) {
                    verArr[i] = Integer.parseInt(arr[i]);
                }
                return verArr;
            }
        }
        return null;
    }

    /**
     * 比较版本号
     *
     * @param ver1
     * @param ver2
     * @return 1:ver1>ver2, 0:ver1=ver2 , -1:ver1<ver2
     */
    public static int compareVersion(String ver1, String ver2) {

        if (ver1.equals(ver2)) {
            return 0;
        }
        int[] ver1Arr = VersionUtil.parseHardvareVersion(ver1);
        int[] ver2Arr = VersionUtil.parseHardvareVersion(ver2);

        int len = Math.min(ver1Arr.length, ver2Arr.length);
        for (int i = 0; i < len; i++) {

            if (ver1Arr[i] > ver2Arr[i]) {
                return 1;
            } else if (ver1Arr[i] < ver2Arr[i]) {
                return -1;
            } else if (ver1Arr[i] == ver2Arr[i]) {
                continue;
            }
        }
        if (ver1Arr.length > ver2Arr.length) {
            return 1;
        } else if (ver1Arr.length < ver2Arr.length) {
            return -1;
        } else {
            return 0;
        }
    }


    public static void main(String[] args) {
        System.out.println(VersionUtil.compareVersion("1.1.0", "1.1.1"));
        System.out.println(VersionUtil.compareVersion("1.1.1", "1.1.1"));
        System.out.println(VersionUtil.compareVersion("1.1.2", "1.1.1"));
        System.out.println(VersionUtil.compareVersion("1.2.0", "1.1.1"));
        System.out.println(VersionUtil.compareVersion("1.2.1", "1.1.1"));
        System.out.println(VersionUtil.compareVersion("1.2.2", "1.1.1"));
    }

}
